package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询商铺类型
     * @return
     */
    @Override
    public Result queryTypeList() {
        //1.查询redis中是否含有所需数据
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String cacheShopJson = opsForValue.get("shop_type");
        //2.判断数据是否为空
        List<ShopType> typeList = new ArrayList<>();
        //2.1 为空
        if(StrUtil.isBlank(cacheShopJson)){
            //从数据库查询数据
            typeList = this
                    .query().orderByAsc("sort").list();
            //将集合对象转换为json格式数据
            String typeJson = JSONUtil.toJsonStr(typeList);
            //将数据存入redis
            opsForValue.set("shop_type", typeJson,30, TimeUnit.MINUTES);
        }else{
            //2.2 不为空
            typeList = JSONUtil.toList(cacheShopJson, ShopType.class);
        }
        return Result.ok(typeList);
    }
}
